<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="通过前面文章详解，我们知道Dubbo服务消费者标签dubbo:reference最终会在Spring容器中创建一个对应的ReferenceBean实例，而ReferenceBean实现了Spring生命周期接口：InitializingBean，接下来应该看一下其afterPropertiesSet方法的实现。">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Dubbo服务消费端启动流程">
<meta property="og:url" content="https://www.codingw.net/posts/cc583494.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="通过前面文章详解，我们知道Dubbo服务消费者标签dubbo:reference最终会在Spring容器中创建一个对应的ReferenceBean实例，而ReferenceBean实现了Spring生命周期接口：InitializingBean，接下来应该看一下其afterPropertiesSet方法的实现。">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdn.net/20180608122049691?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180608122123696?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180608122248962?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="article:published_time" content="2020-11-05T14:57:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:09:46.248Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdn.net/20180608122049691?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/cc583494.html"/>





  <title>源码分析Dubbo服务消费端启动流程 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/cc583494.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Dubbo服务消费端启动流程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-05T22:57:01+08:00">
                2020-11-05
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dubbo/" itemprop="url" rel="index">
                    <span itemprop="name">dubbo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/cc583494.html" class="leancloud_visitors" data-flag-title="源码分析Dubbo服务消费端启动流程">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>通过前面文章详解，我们知道Dubbo服务消费者标签dubbo:reference最终会在Spring容器中创建一个对应的ReferenceBean实例，而ReferenceBean实现了Spring生命周期接口：InitializingBean，接下来应该看一下其afterPropertiesSet方法的实现。</p>
<span id="more"></span>

<h2 id="1、源码分析ReferenceBean-afterPropertiesSet"><a href="#1、源码分析ReferenceBean-afterPropertiesSet" class="headerlink" title="1、源码分析ReferenceBean#afterPropertiesSet"></a>1、源码分析ReferenceBean#afterPropertiesSet</h2><p>ReferenceBean#afterPropertiesSet</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">if (getConsumer() &#x3D;&#x3D; null) &#123;</span><br><span class="line">            Map&lt;String, ConsumerConfig&gt; consumerConfigMap &#x3D; applicationContext &#x3D;&#x3D; null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, </span><br><span class="line">                 ConsumerConfig.class, false, false);</span><br><span class="line">            if (consumerConfigMap !&#x3D; null &amp;&amp; consumerConfigMap.size() &gt; 0) &#123;</span><br><span class="line">                ConsumerConfig consumerConfig &#x3D; null;</span><br><span class="line">                for (ConsumerConfig config : consumerConfigMap.values()) &#123;</span><br><span class="line">                    if (config.isDefault() &#x3D;&#x3D; null || config.isDefault().booleanValue()) &#123;</span><br><span class="line">                        if (consumerConfig !&#x3D; null) &#123;</span><br><span class="line">                            throw new IllegalStateException(&quot;Duplicate consumer configs: &quot; + consumerConfig + &quot; and &quot; + config);</span><br><span class="line">                        &#125;</span><br><span class="line">                        consumerConfig &#x3D; config;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                if (consumerConfig !&#x3D; null) &#123;</span><br><span class="line">                    setConsumer(consumerConfig);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<p>Step1：如果consumer为空，说明dubbo:reference标签未设置consumer属性，如果一个dubbo:consumer标签，则取该实例，如果存在多个dubbo:consumer 配置，则consumer必须设置，否则会抛出异常：”Duplicate consumer configs”。</p>
<p>Step2：如果application为空,则尝试从BeanFactory中查询dubbo:application实例，如果存在多个dubbo:application配置，则抛出异常：”Duplicate application configs”。</p>
<p>Step3：如果ServiceBean的module为空，则尝试从BeanFactory中查询dubbo:module实例，如果存在多个dubbo:module，则抛出异常：”Duplicate module configs: “。</p>
<p>Step4：尝试从BeanFactory中加载所有的注册中心，注意ServiceBean的List&lt; RegistryConfig&gt; registries属性，为注册中心集合。</p>
<p>Step5：尝试从BeanFacotry中加载一个监控中心，填充ServiceBean的MonitorConfig monitor属性，如果存在多个dubbo:monitor配置，则抛出”Duplicate monitor configs: “。</p>
<p>ReferenceBean#afterPropertiesSet</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Boolean b &#x3D; isInit();</span><br><span class="line">if (b &#x3D;&#x3D; null &amp;&amp; getConsumer() !&#x3D; null) &#123;</span><br><span class="line">      b &#x3D; getConsumer().isInit();</span><br><span class="line">&#125;</span><br><span class="line">if (b !&#x3D; null &amp;&amp; b.booleanValue()) &#123;</span><br><span class="line">      getObject();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step6：判断是否初始化，如果为初始化，则调用getObject()方法，该方法也是FactoryBean定义的方法，ReferenceBean是dubbo:reference所真实引用的类(interface)的实例工程，getObject发返回的是interface的实例，而不是ReferenceBean实例。</p>
<h3 id="1-1-源码分析getObject"><a href="#1-1-源码分析getObject" class="headerlink" title="1.1 源码分析getObject()"></a>1.1 源码分析getObject()</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public Object getObject() throws Exception &#123;</span><br><span class="line">        return get();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ReferenceBean#getObject()方法直接调用其父类的get方法,get方法内部调用init()方法进行初始化</p>
<h3 id="1-2-源码分析ReferenceConfig-init方法"><a href="#1-2-源码分析ReferenceConfig-init方法" class="headerlink" title="1.2 源码分析ReferenceConfig#init方法"></a>1.2 源码分析ReferenceConfig#init方法</h3><p>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">if (initialized) &#123;</span><br><span class="line">     return;</span><br><span class="line"> &#125;</span><br><span class="line">initialized &#x3D; true;</span><br><span class="line">if (interfaceName &#x3D;&#x3D; null || interfaceName.length() &#x3D;&#x3D; 0) &#123;</span><br><span class="line">      throw new IllegalStateException(&quot;&lt;dubbo:reference interface&#x3D;\&quot;\&quot; &#x2F;&gt; interface not allow null!&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step1：如果已经初始化，直接返回，如果interfaceName为空，则抛出异常。</p>
<p>ReferenceConfig#init调用ReferenceConfig#checkDefault</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">private void checkDefault() &#123;</span><br><span class="line">        if (consumer &#x3D;&#x3D; null) &#123;</span><br><span class="line">            consumer &#x3D; new ConsumerConfig();</span><br><span class="line">        &#125;</span><br><span class="line">        appendProperties(consumer);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>Step2:如果dubbo:reference标签也就是ReferenceBean的consumer属性为空，调用appendProperties方法，填充默认属性，其具体加载顺序：</p>
<ol>
<li>从系统属性加载对应参数值，参数键：dubbo.consumer.属性名，从系统属性中获取属性值的方法为：System.getProperty(key)。</li>
<li>加载属性配置文件的值。属性配置文件，可通过系统属性：dubbo.properties.file，如果该值未配置，则默认取dubbo.properties属性配置文件。<br>ReferenceConfig#init<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">appendProperties(this);</span><br></pre></td></tr></table></figure>
Step3：调用appendProperties方法，填充ReferenceBean的属性，属性值来源与step2一样，当然只填充ReferenceBean中属性为空的属性。</li>
</ol>
<p>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">if (getGeneric() &#x3D;&#x3D; null &amp;&amp; getConsumer() !&#x3D; null) &#123;</span><br><span class="line">      setGeneric(getConsumer().getGeneric());</span><br><span class="line">&#125;</span><br><span class="line">if (ProtocolUtils.isGeneric(getGeneric())) &#123;</span><br><span class="line">      interfaceClass &#x3D; GenericService.class;</span><br><span class="line">&#125; else &#123;</span><br><span class="line">      try &#123;</span><br><span class="line">              interfaceClass &#x3D; Class.forName(interfaceName, true, Thread.currentThread().getContextClassLoader());</span><br><span class="line">      &#125; catch (ClassNotFoundException e) &#123;</span><br><span class="line">                throw new IllegalStateException(e.getMessage(), e);</span><br><span class="line">      &#125;</span><br><span class="line">      checkInterfaceAndMethods(interfaceClass, methods);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step4：如果使用返回引用，将interface值替换为GenericService全路径名，如果不是，则加载interfacename，并检验dubbo:reference子标签dubbo:method引用的方法是否在interface指定的接口中存在。</p>
<p>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">String resolve &#x3D; System.getProperty(interfaceName);      &#x2F;&#x2F; @1</span><br><span class="line">String resolveFile &#x3D; null;</span><br><span class="line">if (resolve &#x3D;&#x3D; null || resolve.length() &#x3D;&#x3D; 0) &#123;                       &#x2F;&#x2F; @2</span><br><span class="line">     resolveFile &#x3D; System.getProperty(&quot;dubbo.resolve.file&quot;);    &#x2F;&#x2F; @3 start</span><br><span class="line">     if (resolveFile &#x3D;&#x3D; null || resolveFile.length() &#x3D;&#x3D; 0) &#123;</span><br><span class="line">          File userResolveFile &#x3D; new File(new File(System.getProperty(&quot;user.home&quot;)), &quot;dubbo-resolve.properties&quot;);</span><br><span class="line">          if (userResolveFile.exists()) &#123;</span><br><span class="line">               resolveFile &#x3D; userResolveFile.getAbsolutePath();</span><br><span class="line">          &#125;</span><br><span class="line">     &#125;    &#x2F;&#x2F; @3 end</span><br><span class="line">     if (resolveFile !&#x3D; null &amp;&amp; resolveFile.length() &gt; 0) &#123;    &#x2F;&#x2F; @4</span><br><span class="line">          Properties properties &#x3D; new Properties();</span><br><span class="line">          FileInputStream fis &#x3D; null;</span><br><span class="line">          try &#123;</span><br><span class="line">               fis &#x3D; new FileInputStream(new File(resolveFile));</span><br><span class="line">               properties.load(fis);</span><br><span class="line">           &#125; catch (IOException e) &#123;</span><br><span class="line">               throw new IllegalStateException(&quot;Unload &quot; + resolveFile + &quot;, cause: &quot; + e.getMessage(), e);</span><br><span class="line">           &#125; finally &#123;</span><br><span class="line">               try &#123;</span><br><span class="line">                    if (null !&#x3D; fis) fis.close();</span><br><span class="line">                &#125; catch (IOException e) &#123;</span><br><span class="line">                    logger.warn(e.getMessage(), e);</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;</span><br><span class="line">          resolve &#x3D; properties.getProperty(interfaceName);</span><br><span class="line">      &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> if (resolve !&#x3D; null &amp;&amp; resolve.length() &gt; 0) &#123;  &#x2F;&#x2F; @5</span><br><span class="line">      url &#x3D; resolve;</span><br><span class="line">      if (logger.isWarnEnabled()) &#123;</span><br><span class="line">         if (resolveFile !&#x3D; null &amp;&amp; resolveFile.length() &gt; 0) &#123;</span><br><span class="line">             logger.warn(&quot;Using default dubbo resolve file &quot; + resolveFile + &quot; replace &quot; + interfaceName + &quot;&quot; + resolve + &quot; to p2p invoke remote service.&quot;);</span><br><span class="line">         &#125; else &#123;</span><br><span class="line">            logger.warn(&quot;Using -D&quot; + interfaceName + &quot;&#x3D;&quot; + resolve + &quot; to p2p invoke remote service.&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step5：处理dubbo服务消费端resolve机制，也就是说消息消费者只连服务提供者，绕过注册中心。</p>
<ul>
<li>代码@1：从系统属性中获取该接口的直连服务提供者，如果存在 -Dinterface=dubbo://127.0.0.1:20880,其中interface为dubbo:reference interface属性的值。</li>
<li>代码@2：如果未指定-D属性，尝试从resolve配置文件中查找，从这里看出-D的优先级更高。</li>
<li>代码@3：首先尝试获取resolve配置文件的路径，其来源可以通过-Ddubbo.resolve.file=文件路径名来指定，如果未配置该系统参数，则默认从${user.home}/dubbo-resolve.properties,如果过文件存在，则设置resolveFile的值，否则resolveFile为null。</li>
<li>代码@4：如果resolveFile不为空，则加载resolveFile文件中内容，然后通过interface获取其配置的直连服务提供者URL。</li>
<li>代码@5：如果resolve不为空，则填充ReferenceBean的url属性为resolve(点对点服务提供者URL)，打印日志，点对点URL的来源（系统属性、resolve配置文件）。</li>
</ul>
<p>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">checkApplication();</span><br><span class="line">checkStubAndMock(interfaceClass);</span><br></pre></td></tr></table></figure>
<p>Step6：校验ReferenceBean的application是否为空,如果为空，new 一个application，并尝试从系统属性（优先）、资源文件中填充其属性；同时校验stub、mock实现类与interface的兼容性。系统属性、资源文件属性的配置如下：<br>application     dubbo.application.属性名，例如    dubbo.application.name</p>
<p>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;String, String&gt; map &#x3D; new HashMap&lt;String, String&gt;();</span><br><span class="line">Map&lt;Object, Object&gt; attributes &#x3D; new HashMap&lt;Object, Object&gt;();</span><br><span class="line">map.put(Constants.SIDE_KEY, Constants.CONSUMER_SIDE);</span><br><span class="line">map.put(Constants.DUBBO_VERSION_KEY, Version.getVersion());</span><br><span class="line">map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis()));</span><br><span class="line">if (ConfigUtils.getPid() &gt; 0) &#123;</span><br><span class="line">     map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid()));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step7：构建Map,封装服务消费者引用服务提供者URL的属性，这里主要填充side:consume（消费端)、dubbo：2.0.0(版本)、timestamp、pid:进程ID。</p>
<p>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">if (!isGeneric()) &#123;</span><br><span class="line">    String revision &#x3D; Version.getVersion(interfaceClass, version);</span><br><span class="line">    if (revision !&#x3D; null &amp;&amp; revision.length() &gt; 0) &#123;</span><br><span class="line">         map.put(&quot;revision&quot;, revision);</span><br><span class="line">    &#125;</span><br><span class="line">    String[] methods &#x3D; Wrapper.getWrapper(interfaceClass).getMethodNames();</span><br><span class="line">    if (methods.length &#x3D;&#x3D; 0) &#123;</span><br><span class="line">           logger.warn(&quot;NO method found in service interface &quot; + interfaceClass.getName());</span><br><span class="line">           map.put(&quot;methods&quot;, Constants.ANY_VALUE);</span><br><span class="line">     &#125; else &#123;</span><br><span class="line">          map.put(&quot;methods&quot;, StringUtils.join(new HashSet&lt;String&gt;(Arrays.asList(methods)), &quot;,&quot;));</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step8：如果不是泛化引用，增加methods:interface的所有方法名，多个用逗号隔开。<br>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">map.put(Constants.INTERFACE_KEY, interfaceName);</span><br><span class="line">appendParameters(map, application);</span><br><span class="line">appendParameters(map, module);</span><br><span class="line">appendParameters(map, consumer, Constants.DEFAULT_KEY);</span><br><span class="line">appendParameters(map, this);</span><br></pre></td></tr></table></figure>
<p>Step9：用Map存储application配置、module配置、默认消费者参数(ConsumerConfig)、服务消费者dubbo:reference的属性。<br>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">String prefix &#x3D; StringUtils.getServiceKey(map);</span><br><span class="line">if (methods !&#x3D; null &amp;&amp; !methods.isEmpty()) &#123;</span><br><span class="line">    for (MethodConfig method : methods) &#123;</span><br><span class="line">         appendParameters(map, method, method.getName());</span><br><span class="line">         String retryKey &#x3D; method.getName() + &quot;.retry&quot;;</span><br><span class="line">         if (map.containsKey(retryKey)) &#123;</span><br><span class="line">              String retryValue &#x3D; map.remove(retryKey);</span><br><span class="line">              if (&quot;false&quot;.equals(retryValue)) &#123;</span><br><span class="line">                  map.put(method.getName() + &quot;.retries&quot;, &quot;0&quot;);</span><br><span class="line">              &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         appendAttributes(attributes, method, prefix + &quot;.&quot; + method.getName());</span><br><span class="line">         checkAndConvertImplicitConfig(method, map, attributes);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step10：获取服务键值 /{group}/interface:版本，如果group为空，则为interface:版本,其值存为prifex，然后将dubbo:method的属性名称也填入map中，键前缀为dubbo.method.methodname.属性名。dubbo:method的子标签dubbo:argument标签的属性也追加到attributes map中，键为 prifex + methodname.属性名。</p>
<p>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">String hostToRegistry &#x3D; ConfigUtils.getSystemProperty(Constants.DUBBO_IP_TO_REGISTRY);</span><br><span class="line">if (hostToRegistry &#x3D;&#x3D; null || hostToRegistry.length() &#x3D;&#x3D; 0) &#123;</span><br><span class="line">      hostToRegistry &#x3D; NetUtils.getLocalHost();</span><br><span class="line">&#125; else if (isInvalidLocalHost(hostToRegistry)) &#123;</span><br><span class="line">      throw new IllegalArgumentException(&quot;Specified invalid registry ip from property:&quot; + Constants.DUBBO_IP_TO_REGISTRY + &quot;, value:&quot; + </span><br><span class="line">           hostToRegistry);</span><br><span class="line">&#125;</span><br><span class="line">map.put(Constants.REGISTER_IP_KEY, hostToRegistry);</span><br></pre></td></tr></table></figure>
<p>Step11：填充register.ip属性，该属性是消息消费者连接注册中心的IP，并不是注册中心自身的IP。<br>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ref &#x3D; createProxy(map);</span><br></pre></td></tr></table></figure>
<p>Step12：调用createProxy方法创建消息消费者代理，下面详细分析其实现细节。<br>ReferenceConfig#init</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ConsumerModel consumerModel &#x3D; new ConsumerModel(getUniqueServiceName(), this, ref, interfaceClass.getMethods());</span><br><span class="line">ApplicationModel.initConsumerModel(getUniqueServiceName(), consumerModel);</span><br></pre></td></tr></table></figure>
<p>Step13：将消息消费者缓存在ApplicationModel中。</p>
<h4 id="1-2-1-源码分析ReferenceConfig-createProxy方法"><a href="#1-2-1-源码分析ReferenceConfig-createProxy方法" class="headerlink" title="1.2.1 源码分析ReferenceConfig#createProxy方法"></a>1.2.1 源码分析ReferenceConfig#createProxy方法</h4><p>ReferenceConfig#createProxy</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">URL tmpUrl &#x3D; new URL(&quot;temp&quot;, &quot;localhost&quot;, 0, map);</span><br><span class="line">final boolean isJvmRefer;</span><br><span class="line">if (isInjvm() &#x3D;&#x3D; null) &#123;</span><br><span class="line">    if (url !&#x3D; null &amp;&amp; url.length() &gt; 0) &#123; &#x2F;&#x2F; if a url is specified, don&#39;t do local reference</span><br><span class="line">          isJvmRefer &#x3D; false;</span><br><span class="line">    &#125; else if (InjvmProtocol.getInjvmProtocol().isInjvmRefer(tmpUrl)) &#123;</span><br><span class="line">         &#x2F;&#x2F; by default, reference local service if there is</span><br><span class="line">         isJvmRefer &#x3D; true;</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">         isJvmRefer &#x3D; false;</span><br><span class="line">    &#125;</span><br><span class="line">&#125; else &#123;</span><br><span class="line">    isJvmRefer &#x3D; isInjvm().booleanValue();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step1：判断该消费者是否是引用本(JVM)内提供的服务。<br>如果dubbo:reference标签的injvm(已过期，被local属性替换)如果不为空，则直接取该值，如果该值未配置，则判断ReferenceConfig的url属性是否为空，如果不为空，则isJvmRefer =false，表明该服务消费者将直连该URL的服务提供者；如果url属性为空，则判断该协议是否是isInjvm，其实现逻辑：获取dubbo:reference的scop属性，根据其值判断：</p>
<ul>
<li>如果为空，isJvmRefer为false。</li>
<li>如果协议为injvm，就是表示为本地协议，既然提供了本地协议的实现，则无需配置isJvmRefer该标签为true，故，isJvmRerfer=false。</li>
<li> 如果scope=local或injvm=true，isJvmRefer=true。</li>
<li>如果scope=remote，isJvmRefer设置为false。</li>
<li>如果是泛化引用，isJvmRefer设置为false。</li>
<li>其他默认情况，isJvmRefer设置为true。</li>
</ul>
<p>ReferenceConfig#createProxy</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">if (isJvmRefer) &#123;</span><br><span class="line">   URL url &#x3D; new URL(Constants.LOCAL_PROTOCOL, NetUtils.LOCALHOST, 0, interfaceClass.getName()).addParameters(map);</span><br><span class="line">   invoker &#x3D; refprotocol.refer(interfaceClass, url);</span><br><span class="line">   if (logger.isInfoEnabled()) &#123;</span><br><span class="line">         logger.info(&quot;Using injvm service &quot; + interfaceClass.getName());</span><br><span class="line">   &#125;</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>Step2：如果消费者引用本地JVM中的服务，则利用InjvmProtocol创建Invoker，dubbo中的invoker主要负责服务调用的功能，是其核心实现，后续会在专门的章节中详细分析，在这里我们需要知道，会创建于协议相关的Invoker即可。</p>
<p>ReferenceConfig#createProxy</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">if (url !&#x3D; null &amp;&amp; url.length() &gt; 0) &#123; &#x2F;&#x2F; user specified URL, could be peer-to-peer address, or register center&#39;s address.</span><br><span class="line">     String[] us &#x3D; Constants.SEMICOLON_SPLIT_PATTERN.split(url);   &#x2F;&#x2F; @1</span><br><span class="line">     if (us !&#x3D; null &amp;&amp; us.length &gt; 0) &#123;</span><br><span class="line">           for (String u : us) &#123;</span><br><span class="line">                  URL url &#x3D; URL.valueOf(u);</span><br><span class="line">                  if (url.getPath() &#x3D;&#x3D; null || url.getPath().length() &#x3D;&#x3D; 0) &#123;</span><br><span class="line">                       url &#x3D; url.setPath(interfaceName);</span><br><span class="line">                  &#125;</span><br><span class="line">                 if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) &#123;   &#x2F;&#x2F; @2</span><br><span class="line">                      urls.add(url.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map)));</span><br><span class="line">                  &#125; else &#123;</span><br><span class="line">                      urls.add(ClusterUtils.mergeUrl(url, map));  &#x2F;&#x2F; @3</span><br><span class="line">                 &#125;</span><br><span class="line">             &#125;</span><br><span class="line">       &#125;</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>Step3：处理直连情况，与step2互斥。</p>
<ul>
<li>代码@1：对直连URL进行分割，多个直连URL用分号隔开，如果URL中不包含path属性，则为URL设置path属性为interfaceName。</li>
<li>代码@2：如果直连提供者的协议为registry，则对url增加refer属性，其值为消息消费者所有的属性。(表示从注册中心发现服务提供者)</li>
<li>代码@3：如果是其他协议提供者，则合并服务提供者与消息消费者的属性，并移除服务提供者默认属性。以default开头的属性。</li>
</ul>
<p>ReferenceConfig#createProxy</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">List&lt;URL&gt; us &#x3D; loadRegistries(false);   &#x2F;&#x2F; @1</span><br><span class="line">if (us !&#x3D; null &amp;&amp; !us.isEmpty()) &#123;</span><br><span class="line">     for (URL u : us) &#123;</span><br><span class="line">           URL monitorUrl &#x3D; loadMonitor(u);   &#x2F;&#x2F; @2</span><br><span class="line">           if (monitorUrl !&#x3D; null) &#123;</span><br><span class="line">                 map.put(Constants.MONITOR_KEY, URL.encode(monitorUrl.toFullString()));   &#x2F;&#x2F; @3</span><br><span class="line">            &#125;</span><br><span class="line">            urls.add(u.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map)));  &#x2F;&#x2F; @4</span><br><span class="line">       &#125;</span><br><span class="line">&#125;</span><br><span class="line">if (urls &#x3D;&#x3D; null || urls.isEmpty()) &#123;</span><br><span class="line">       throw new IllegalStateException(&quot;No such any registry to reference &quot; + interfaceName + &quot; on the consumer &quot; + NetUtils.getLocalHost() + &quot; use dubbo version &quot; + Version.getVersion() + &quot;, please config &lt;dubbo:registry </span><br><span class="line">          address&#x3D;\&quot;...\&quot; &#x2F;&gt; to your spring config.&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step4：普通消息消费者，从注册中心订阅服务。</p>
<ul>
<li>代码@1：获取所有注册中心URL，其中参数false表示消费端，需要排除dubbo:registry subscribe=false的注册中心，其值为false表示不接受订阅。</li>
<li>代码@2：根据注册中心URL，构建监控中心URL。</li>
<li>代码@3：如果监控中心不为空，在注册中心URL后增加属性monitor。</li>
<li>代码@4：在注册中心URL中，追加属性refer，其值为消费端的所有配置组成的URL。</li>
</ul>
<p>ReferenceConfig#createProxy</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">if (urls.size() &#x3D;&#x3D; 1) &#123;</span><br><span class="line">    invoker &#x3D; refprotocol.refer(interfaceClass, urls.get(0));     &#x2F;&#x2F; @1</span><br><span class="line">&#125; else &#123;</span><br><span class="line">    List&lt;Invoker&lt;?&gt;&gt; invokers &#x3D; new ArrayList&lt;Invoker&lt;?&gt;&gt;();    &#x2F;&#x2F; @2,多个服务提供者URL，集群模式</span><br><span class="line">    URL registryURL &#x3D; null;</span><br><span class="line">    for (URL url : urls) &#123;</span><br><span class="line">         invokers.add(refprotocol.refer(interfaceClass, url));    &#x2F;&#x2F; @2</span><br><span class="line">         if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) &#123;</span><br><span class="line">               registryURL &#x3D; url; &#x2F;&#x2F; use last registry url</span><br><span class="line">          &#125;</span><br><span class="line">     &#125;</span><br><span class="line">     if (registryURL !&#x3D; null) &#123; &#x2F;&#x2F; registry url is available</span><br><span class="line">          &#x2F;&#x2F; use AvailableCluster only when register&#39;s cluster is available</span><br><span class="line">          URL u &#x3D; registryURL.addParameter(Constants.CLUSTER_KEY, AvailableCluster.NAME);</span><br><span class="line">          invoker &#x3D; cluster.join(new StaticDirectory(u, invokers));    &#x2F;&#x2F; @3</span><br><span class="line">     &#125; else &#123; &#x2F;&#x2F; not a registry url</span><br><span class="line">          invoker &#x3D; cluster.join(new StaticDirectory(invokers));</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>Step5：根据URL获取对应协议的Invoker。</p>
<ul>
<li>代码@1：如果只有一个服务提供者URL,则直接根据协议构建Invoker，具体有如下协议：<br><img src="https://img-blog.csdn.net/20180608122049691?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"></li>
<li>代码@2：如果有多个服务提供者，则众多服务提供者构成一个集群。<br>首先根据协议构建服务Invoker，默认Dubbo基于服务注册于发现，在服务消费端不会指定url属性，从注册中心获取服务提供者列表，此时的URL：registry://开头，url中会包含register属性，其值为注册中心的类型，例如zookeeper，将使用RedisProtocol构建Invoker，该方法将自动发现注册在注册中心的服务提供者，后续文章将会zookeeper注册中心为例，详细分析其实现原理。</li>
<li>代码@3：返回集群模式实现的Invoker，Dubbo中的Invoker类继承体系如下：<br><img src="https://img-blog.csdn.net/20180608122123696?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>集群模式的Invoker和单个协议Invoker一样实现Invoker接口，然后在集群Invoker中利用Directory保证一个一个协议的调用器，十分的巧妙，在后续章节中将重点分析Dubbo Invoker实现原理，包含集群实现机制。</li>
</ul>
<p>ReferenceConfig#createProxy</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Boolean c &#x3D; check;</span><br><span class="line">if (c &#x3D;&#x3D; null &amp;&amp; consumer !&#x3D; null) &#123;</span><br><span class="line">      c &#x3D; consumer.isCheck();</span><br><span class="line">&#125;</span><br><span class="line">if (c &#x3D;&#x3D; null) &#123;</span><br><span class="line">      c &#x3D; true; &#x2F;&#x2F; default true</span><br><span class="line">&#125;</span><br><span class="line">if (c &amp;&amp; !invoker.isAvailable()) &#123;</span><br><span class="line">       throw new IllegalStateException(&quot;Failed to check the status of the service &quot; + interfaceName + &quot;. No provider available for the service &quot; + (group   </span><br><span class="line">              &#x3D;&#x3D; null ? &quot;&quot; : group + &quot;&#x2F;&quot;) + interfaceName + (version &#x3D;&#x3D; null ? &quot;&quot; : &quot;:&quot; + version) + &quot; from the url &quot; + invoker.getUrl() + &quot; to the consumer &quot; + </span><br><span class="line">             NetUtils.getLocalHost() + &quot; use dubbo version &quot; + Version.getVersion());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>代码@4：如果dubbo:referecnce的check=true或默认为空，则需要判断服务提供者是否存在。</li>
</ul>
<p>ReferenceConfig#createProxy</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">return (T) proxyFactory.getProxy(invoker);</span><br><span class="line">AbstractProxyFactory#getProxy</span><br><span class="line">public &lt;T&gt; T getProxy(Invoker&lt;T&gt; invoker) throws RpcException &#123;</span><br><span class="line">        Class&lt;?&gt;[] interfaces &#x3D; null;</span><br><span class="line">        String config &#x3D; invoker.getUrl().getParameter(&quot;interfaces&quot;);     &#x2F;&#x2F; @1</span><br><span class="line">        if (config !&#x3D; null &amp;&amp; config.length() &gt; 0) &#123;</span><br><span class="line">            String[] types &#x3D; Constants.COMMA_SPLIT_PATTERN.split(config);</span><br><span class="line">            if (types !&#x3D; null &amp;&amp; types.length &gt; 0) &#123;</span><br><span class="line">                interfaces &#x3D; new Class&lt;?&gt;[types.length + 2];</span><br><span class="line">                interfaces[0] &#x3D; invoker.getInterface();</span><br><span class="line">                interfaces[1] &#x3D; EchoService.class;        &#x2F;&#x2F; @2</span><br><span class="line">                for (int i &#x3D; 0; i &lt; types.length; i++) &#123;</span><br><span class="line">                    interfaces[i + 1] &#x3D; ReflectUtils.forName(types[i]);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        if (interfaces &#x3D;&#x3D; null) &#123;</span><br><span class="line">            interfaces &#x3D; new Class&lt;?&gt;[]&#123;invoker.getInterface(), EchoService.class&#125;;</span><br><span class="line">        &#125;</span><br><span class="line">        return getProxy(invoker, interfaces);    &#x2F;&#x2F; @3</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>根据invoker获取代理类，其实现逻辑如下：</p>
<ul>
<li>代码@1：从消费者URL中获取interfaces的值，用,分隔出单个服务应用接口。</li>
<li>代码@2：增加默认接口EchoService接口。</li>
<li>代码@3:根据需要实现的接口，使用jdk或Javassist创建代理类。<br>最后给出消息消费者启动时序图：<br><img src="https://img-blog.csdn.net/20180608122248962?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>本节关于Dubbo服务消费者（服务调用者）的启动流程就梳理到这里，下一篇将重点关注Invoker（服务调用相关的实现细节）。</li>
</ul>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/7c2dea71.html" rel="next" title="源码分析Dubbo服务注册与发现机制RegistryDirectory)">
                <i class="fa fa-chevron-left"></i> 源码分析Dubbo服务注册与发现机制RegistryDirectory)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/380ae8bd.html" rel="prev" title="源码分析Dubbo服务提供者启动流程-下篇">
                源码分析Dubbo服务提供者启动流程-下篇 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90ReferenceBean-afterPropertiesSet"><span class="nav-number">1.</span> <span class="nav-text">1、源码分析ReferenceBean#afterPropertiesSet</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90getObject"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 源码分析getObject()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90ReferenceConfig-init%E6%96%B9%E6%B3%95"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 源码分析ReferenceConfig#init方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-1-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90ReferenceConfig-createProxy%E6%96%B9%E6%B3%95"><span class="nav-number">1.2.1.</span> <span class="nav-text">1.2.1 源码分析ReferenceConfig#createProxy方法</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
